import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:ulearning_app/common/global_loader/global_loader.dart';
import 'package:ulearning_app/common/widgets/popup_messages.dart';
import 'package:ulearning_app/pages/sign_up/notifier/register_notifier.dart';

class SignUpController {
  final WidgetRef ref;
  SignUpController({required this.ref});

  //
  Future<void> handleSignUp() async {
    var state = ref.read(registerNotifierProvider);
    String name = state.userName;

    String email = state.email;
    String password = state.password;
    String confirmPassword = state.confirmPassword;
    if (name.isEmpty) {
      toastInfo("请输入用户名");
      return;
    }
    if (name.length < 6) {
      toastInfo("用户名长度不能小于6位");
      return;
    }
    if (email.isEmpty) {
      toastInfo("请输入邮箱");
      return;
    }
    if (password.isEmpty) {
      toastInfo("请输入密码");
      return;
    }
    if (password.length < 6) {
      toastInfo("密码长度不能小于6位");
      return;
    }
    if (confirmPassword.isEmpty) {
      toastInfo("请确认密码");
      return;
    }

    if (confirmPassword.length < 6) {
      toastInfo("确认密码长度不能小于6位");
      return;
    }
    if (password != confirmPassword) {
      toastInfo("您的密码不匹配");
      return;
    }

    ref.read(appLoaderProvider.notifier).setLoading(true); //显示加载动画
    try {
      final credential =
          await FirebaseAuth.instance.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
      if (kDebugMode) {
        print(credential);
      }
      if (credential.user != null) {
        await credential.user?.sendEmailVerification(); //发送验证邮件
        await credential.user?.updateDisplayName(name); //更新用户名
        toastInfo("注册成功，请验证邮箱");
        Navigator.pop(ref.context);
      }
    } catch (e) {
      toastInfo(e.toString());
    }
    ref.watch(appLoaderProvider.notifier).setLoading(false); //隐藏加载动画
  }
}
